
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanflutter/ui/page/page_webview.dart';

import '../../http/api.dart';
import '../widget/article_item.dart';
import '../widget/banner_view.dart';

class ArticlePage extends StatefulWidget{
  @override
  _ArticlePageState createState() => _ArticlePageState();
}

class _ArticlePageState extends State<ArticlePage> {
  ///上下滑动控制器
  ScrollController _controller = new ScrollController();

  ///正在加载的标识
  bool _isLoading = true;

  ///请求到的数据
  List articles = [];

  ///banner图
  List banners = [];

  ///文章的总数
  var listTotalSize = 0;

  ///文章的当前页码
  var curPage = 0;


  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      ///获得ScrollController监听控件的的最大滚动范围
      var maxScroll = _controller.position.maxScrollExtent;

      ///获取当前位置的像素值??
      var pixels = _controller.position.pixels;
      ///当前滑动位置到达底部时 加载更多数据
      if(maxScroll == pixels && articles.length < listTotalSize) {
        ///加载更多
        _getArticlelist();
      }
    });
    _pullToRefresh();
  }


  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // 异步任务获取更多文章数据
  _getArticlelist({bool update = true}) async {
    var data = await Api.getArticleList(curPage);
    if(data != null){
      var map = data['data'];
      var datas = map['datas'];

      ///获取具体文章总数
      listTotalSize = map['total'];
      if(curPage == 0) {
        articles.clear();
      }
      curPage++;
      articles.addAll(datas);

      /// 获取新的数据后更新ui
      if (update){
        setState(() { });
      }
    }
  }

  /// 刷新banner的
  _getBanner([bool update = true]) async {
    var data = await Api.getBanner();
    if (data != null) {
      banners.clear();
      banners.addAll(data['data']);
      if(update){
        setState(() {
        });
      }
    }
  }

  ///内容刷新功能,下拉刷新
  Future<void> _pullToRefresh() async {
    curPage = 0;
    /// Future的有序任务列，异步顺序执行
    Iterable<Future> futures = [_getArticlelist(), _getBanner()];
    await Future.wait(futures);
    _isLoading =false;
    setState(() {
    });
    return;
  }
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        /// 正在加载中的圈
        Offstage(
          offstage: !_isLoading, //是否隐藏判断,true则隐藏
          child: Center(child: CircularProgressIndicator()),
        ),

        ///文章内容加载
        Offstage(
          offstage: _isLoading,
          child: RefreshIndicator(
              onRefresh: _pullToRefresh,
              child: ListView.builder(
                  itemCount: articles.length + 1, // 内容目标数量
                  itemBuilder: (context, i) => _buildItem(i), //内容排布
                  controller: _controller, //滚动控制器
              ),
          ),
        ),
      ],
    );
  }

  Widget _buildItem(int i) {
    if(i == 0) {
      return Container(
        height: 180.0,
        child: _bannerView(),  //顶部第一行显示一个banner
      );
    }
    var itemData = articles[i - 1];
    return new ArticleItem(itemData);
  }

  BannerView? _bannerView() {
    var list = banners.map((item){ // map方法将列表中的每个对象item执行遍历封装为InkWell可点击控件
      return InkWell(
        child: Image.network(item['imagePath'], fit: BoxFit.cover,), //获取网络图片，并填充满框
        onTap: (){  //添加每个banner图的点击事件，跳转打开指定网页
          Navigator.push(context, MaterialPageRoute(builder: (_) {
            return WebViewPage(item);
          }));
        },
      );
    }).toList(); //转为InkWell控件的列表
    /// 将数据列表封装为banner类型，返回banner对象
    return list.isNotEmpty?
        /// BannerView无法非空已淘汰
        BannerView(
          list,
          const Duration(seconds: 5),
        ) : null;
  }

}